<?php
namespace app\index\controller;

use app\admin\model\WechatMessage;
use think\Controller;
use think\Db;
use think\Request;
use think\Validate;

class Dingding extends Controller
{
	/**
	 * 获取access_token
	 * TODO：之后需要更换成第三方企业获取token；文档地址:https://open.dingtalk.com/document/isvapp-server/obtains-the-enterprise-authorized-credential
	 * */
	public function getToken()
	{
		$json = file_get_contents(RUNTIME_PATH . 'dd_access_token.json');
		$result = json_decode($json, true);
		if (!$result || !$result['access_token'] || $result['expires_time'] <= time()) {
			// 重新获取token
			$url = 'https://oapi.dingtalk.com/gettoken';
			$appkey = 'dingjy2rwixyh022yd05';
			$appsecret = 'XfnBtbudzFmlLUNCK5MI3uAl-xzwsSqUXg92lqRXcIsEeTEDxpHUsepghsdQo6oM';

			$url = $url . '?appkey=' . $appkey . '&appsecret=' . $appsecret;

			$json = file_get_contents($url);
			$result = json_decode($json, true);
			if ($result['errcode'] == 0) {
				$result['expires_time'] = time() + $result['expires_in'] - 60;

				file_put_contents(RUNTIME_PATH . 'dd_access_token.json', json_encode($result));
			} else {
				apiReturn(2, 'token获取失败');
			}
		}

		return $result['access_token'];
	}

	public function ddLogin()
	{
		$input = Request()->param();

		$code = $input['code'];

		if (empty($code)) apiReturn(2, 'code缺失');

		$access_token = $this->getToken();
		$url = 'https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token=' . $access_token;

		$data = [
			'code' => $code
		];

		$info = httpsRequest($url, $data);
		$info = json_decode($info, true);

		if ($info['errcode'] == 0) {
			apiReturn(1, '登录成功', $info['result']);
		} else {
			apiReturn(2, $info['errcode']);
		}
	}

	//更新openid
	public function saveDdUserInfo()
	{
		$input = Request()->param();

		$uid = $input['uid'];
		$userid = $input['userid'];
		$unionid = $input['unionid'];

		if (empty($uid)) apiReturn(2, '用户ID不能为空');
		if (empty($userid)) apiReturn(2, 'userid不能为空');

		$res = db('user')->where(['id' => $uid])->update(['dd_unionid' => $unionid, 'dd_userid' => $userid]);

		if ($res) {
			return apireturn(1, '成功');
		} else {
			return apireturn(2, '失败');
		}
	}
}
